package forum.service.shiro_test;

import com.foreveross.springboot.dubbo.utils.Payload;
import forum.domain.Token;
import forum.domain.User;
import forum.domain.UserRole;
import forum.repository.UserRepository;
import forum.repository.UserRoleRepository;
import forum.service.rpc.api.TokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.util.*;


/**
 * Shiro测试Controller
 *
 * @author   ClownMonkey(87406054)
 * @myblog
 * @create    2016年12月13日
 */
@RestController
@RequestMapping(value = "/apis/shiro")
public class ShiroController {
	
	private static final Logger logger = LoggerFactory.getLogger(ShiroController.class);
		
	@Autowired
	private UserRepository userRepository;

    @Autowired
    private UserRoleRepository user_RoleRepository;


    @Autowired
    private TokenService tokenService;

	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String loginForm(){
		return "login please";
	}

    @RequestMapping(value="/test",method=RequestMethod.GET)
    public String logintest(){
        return "test";
    }

    Map<String,Object> map = new HashMap<String, Object>();
	@RequestMapping(value="/login",method=RequestMethod.POST)
    public Payload login(@RequestBody Map<String, String> params) {

        System.out.println("总共获取到："+params.size()+"个参数");
        for(String key : params.keySet()){
            System.out.println(key + " : " + params.get(key));
        }

        String username = params.get("username");
        String password = params.get("password");
//		UsernamePasswordToken token = new UsernamePasswordToken(params.get("username"), params.get("password"));
        Map<String,String> error = new HashMap<String, String>();
        //验证是否登录成功
        Map<String,Object> map = new HashMap<String, Object>();

        List<User> _username = userRepository.findByUsername(username);
        if(_username!=null&&_username.size()>0){
            if(_username.get(0).getPassword().toString().trim().equals(password)){
//                map.put("success","1");
                logger.info("验证开始");
                Token _token =new Token();

                _token.setTokenpassword(password);
                _token.setTokenusername(username);

                _token.setTokenname(tokenService.createCode());
               Token token = (Token) tokenService.createToken(_token);
                map.put("success","1");
                map.put("token",token);
                List<UserRole> userRoleList =user_RoleRepository.findByUsername(username);
                if (userRoleList.size()>0&&userRoleList!=null){
                   String role=userRoleList.get(0).getRole().getRolename().toString().trim();
                    map.put("role",role);
                }else{
                    map.put("role",null);
                }

            }else {
                error.put("error","密码错误");
                error.put("fail","0");
                return new Payload(error);
            }
        }else {
            error.put("error","用户名不存在");
            error.put("fail","0");
            return new Payload(error);
        }
        return new Payload(map);
	}


    @RequestMapping(value="/time",method= RequestMethod.GET)
    public String hehe() {
        return "现在时间：" + (new Date()).toLocaleString();
    }
	
	@RequestMapping(value="/logout",method=RequestMethod.PUT)
    public Payload logout( @QueryParam("token") @DefaultValue("null") String token){
        logger.info("退出"+token+"开始");
        tokenService.deleteTokenByTokenname(token);
        map.put("msg","您已安全退出");
        return new Payload("您已安全退出");
    }

    @RequestMapping(value="/logout",method=RequestMethod.GET)
    public Payload logout2( @QueryParam("token") @DefaultValue("null") String token){
        logger.info("退出"+token+"开始");
        tokenService.deleteTokenByTokenname(token);
        map.put("msg","您已安全退出");
        map.put("success",1);
        return new Payload(map);
    }

    @RequestMapping(value="/logout",method=RequestMethod.POST)
    public Payload logout3(@RequestBody Map<String, String> params) {

        System.out.println("总共获取到："+params.size()+"个参数");
        for(String key : params.keySet()){
            System.out.println(key + " : " + params.get(key));
        }
       String token= params.get("token").toString().trim();
        logger.info("退出"+token+"开始");
        tokenService.deleteTokenByTokenname(token);
        return new Payload("您已安全退出");

    }

	@RequestMapping("/403")
	public Payload unauthorizedRole(){
		logger.info("------没有权限-------");
        return new Payload("没有权限");
	}

}
